﻿using IDapperRepository;
using Microsoft.Extensions.Logging;
using MineMES.Application.AppHelper;
using MineMES.Application.DTO;
using MineMES.Domain.Entity;
using MineMES.EntityFrameworkCore;
using MongoDbRepository;
using NPOI.HSSF.UserModel;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MineMES.Application
{
    public class SysUserApps
    {
        private readonly ILogger _logger;
        private readonly MineMESDbContext _context;
        private readonly IDapperBaseRepository<Sys_User> _dapperBaseRepository;
        private readonly MongoDBHelper mongo = new MongoDBHelper();
        private Result result = new Result();
        public SysUserApps(ILogger<SysUserApps> logger, MineMESDbContext Context, IDapperBaseRepository<Sys_User> dapperBaseRepository)
        {
            _logger = logger;
            _context = Context;
            _dapperBaseRepository = dapperBaseRepository;
        }

        public async Task<Result> Load(Request request)
        {
            string sql = "select row_number() over (ORDER BY createdate desc) num,* from Sys_User";
            var query = from depart in _context.Sys_Depart 
                        join users in _context.Sys_Users 
                        on depart.UserNo equals users.UserNo
                        select new {users.UserName};
            return await _dapperBaseRepository.GetDataBySqlByPage(sql, request.pageSize, request.pageNum);
        }

        public Result Log(SysUserDto logUser)
        {
            if (logUser.UserNo == "admin")
            {
                var tokenStr = GetToken.Login(logUser);
                mongo.Insert(logUser);
                result.IsSuccess = true;
                result.Message = tokenStr;
            }
            else
            {
                result.IsSuccess = false;
            }
            return result;
        }

        public Sys_User GetById(string userId)
        {
            return _context.Sys_Users.FirstOrDefault(x => x.Id == userId);
        }

        public Result Add(Sys_User sysUser)
        {
            _context.Add<Sys_User>(sysUser);
            _context.SaveChanges();
            result = new Result();
            result.IsSuccess = true;
            result.Code = 200;
            result.Message = "创建完成";
            result.Data = null;
            return result;
        }

        public Result Update(Sys_User sysUser)
        {
            result = new Result();
            //_context.Update<Sys_User>(sysUser);
            _context.Attach(sysUser);
            _context.Entry(sysUser).Property(p => p.UserNo).IsModified = true;
            _context.Entry(sysUser).Property(p => p.UserName).IsModified = true;
            _context.Entry(sysUser).Property(p => p.DependDepartNo).IsModified = true;
            _context.Entry(sysUser).Property(p => p.Address).IsModified = true;
            _context.SaveChanges();
            result.IsSuccess = true;
            result.Code = 200;
            result.Message = "更新完成";
            result.Data = null;
            return result;
        }

        public Result Delete(string userIds)
        {
            var idArr = userIds.Split(',');
            _context.RemoveRange(_context.Sys_Users.Where(x => idArr.Contains(x.Id)));
            _context.SaveChanges();
            result.IsSuccess = true;
            result.Code = 200;
            result.Message = "删除成功";
            result.Data = null;
            return result;
        }

        public Result Export()
        {
            result = new Result();
            //创建工作薄
            var workbook = new HSSFWorkbook();
            //创建表
            var table = workbook.CreateSheet("joye.net");

            //模拟20行20列数据
            for (var i = 0; i < 20; i++)
            {
                var row = table.CreateRow(i);
                for (int j = 0; j < 20; j++)
                {
                    var cell = row.CreateCell(j);
                    cell.SetCellValue(j);
                }
            }
            //打开xls文件，如没有则创建，如存在则在创建是不要打开该文件
            using (var fs = File.OpenWrite(@"c:/joye.net.xls"))
            {
                workbook.Write(fs);   //向打开的这个xls文件中写入mySheet表并保存。
                Console.WriteLine("生成成功");
            }
            return result;
        }

    }
}
